<?php

namespace Mall\Model;

use Common\Model\BaseModel;
use Common\Model\ModelException;
use Util\ModelUtils;
use Carbon\Carbon;

class GoodsCommentModel extends BaseModel
{
    protected $_auto = [
        ['create_time', 'time', self::MODEL_INSERT, 'function'],
        ['body', 'replaceBadWord', self::MODEL_BOTH, 'callback'],
    ];

    protected $_validate = [
    ];

    protected $_scope = [
        'valid' => [
            'where' => [
                'is_checked' => 'Y',
            ]
        ]
    ];

    /**
     * 过滤敏感词
     * @param string $data
     * @return string
     */
    protected function replaceBadWord($data)
    {
        // 因为后台管理与API不在同一项目，故不能使用缓存
        $v = unserialize(D('Setting')->getByK('articlesensitivewords')['v']);
        $words = empty($v['word']) ? [] : explode('|', trim($v['word'], '|'));
        return filter_badwords($data, $words);
    }

    protected function _after_find(&$record, $options)
    {
        Carbon::setLocale('zh');
        $record['pics'] = $record['pics'] ? explode(',', $record['pics']): [];
        $record['human_time'] = Carbon::createFromTimestamp($record['create_time'])->diffForHumans();
    }

    protected function _after_select(&$records, $options)
    {
        Carbon::setLocale('zh');
        foreach ($records as &$record) {
            $record['pics'] = $record['pics'] ? explode(',', $record['pics']): [];
            $record['human_time'] = Carbon::createFromTimestamp($record['create_time'])->diffForHumans();
        }
    }
    
}
